package com.qfmy.mystation.utils;

import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import timber.log.Timber;

public class SaveBitmapToDIMIUtil {
    public static String saveBitmap(Bitmap bitmap, String path) {
        String savePath;
        File filePic;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            savePath = path;
        } else {
            Timber.tag("tag").e("saveBitmap failure : sdcard not mounted");
            return null;
        }
        try {
            filePic = new File(savePath);
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            Timber.tag("tag").e("saveBitmap: %s", e.getMessage());
            return null;
        }
        Timber.tag("tag").i("saveBitmap success: %s", filePic.getAbsolutePath());
        return filePic.getAbsolutePath();
    }

    public static void saveImage29(Context context, Bitmap toBitmap) {
        //开始一个新的进程执行保存图片的操作
        Uri insertUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        //使用use可以自动关闭流
        try {
            OutputStream outputStream = context.getContentResolver().openOutputStream(insertUri, "rw");
            if (toBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)) {
                Timber.tag("图片保存成功").e("success");
            } else {
                Timber.tag("图片保存失败").e("fail");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
